import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:series_play/comm/sp_constant.dart';
import 'package:series_play/utils/sp.dart';
import 'dart:ui' as ui;

class LocalTool {

  LocalTool._();

  static const locals = [
    Locale('en', 'US'),
    Locale('zh', 'Hans'),
    Locale('zh', 'Hant'),
    Locale('fr', 'FR'),
  ];

  static Future<Locale> currentLocal() async {
    var defaultLocalIndex = await Sp.getInt(
      SpConstant.appLanguageType,
      def: -1,
    );
    if (defaultLocalIndex == -1) {
      // 系统语言
      final sysLocal = ui.PlatformDispatcher.instance.locale;
      for (int i = 0; i < locals.length; i++) {
        if (locals[i].languageCode == sysLocal.languageCode) {
          defaultLocalIndex = i;
          await Sp.putInt(SpConstant.appLanguageType, defaultLocalIndex);
          break;
        }
      }
      if (defaultLocalIndex == -1) {
        defaultLocalIndex = 0;
        await Sp.putInt(SpConstant.appLanguageType, defaultLocalIndex);
      }
    }
    return locals[defaultLocalIndex];
  }

  // en_US zn_Hans zh-Hant fr_FR
  static changeLanguage(int index) async {
    final local = locals[index];
    await Sp.putInt(SpConstant.appLanguageType, index);
    await Get.updateLocale(local);
  }
}
